package com.yjx.gulimall.product.execption;

import com.yjx.gulimall.common.exception.StatusCodeEnum;
import com.yjx.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = {"com.yjx.gulimall.product.controller"})
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException validException){
        log.error("数据校验异常",validException.getMessage());
        BindingResult bindingResult = validException.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> errorMap = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return R.error(StatusCodeEnum.VALID_EXCEPTION.getCode(),StatusCodeEnum.UNKNOW_EXCEPTION.getMsg()).put("data",errorMap);
    }
}
